﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using Zero.UControl.Component.Command;
using Zero.UControl.Component.Common;
using Zero.UControl.Component.MsgBox;

namespace Zero.UControl.Component
{
    /// <summary>
    /// UTabControl.xaml 的交互逻辑
    /// </summary>
    public partial class UTabControl : UserControl
    {
        public UTabControl()
        {
            InitializeComponent();
            ToTargetNavCommand = new BaseCommand<TabNavItem>(ToTargetNav, null);
        }

        #region 字段
        private static Dictionary<string, FrameworkElement> ElemDict = new Dictionary<string, FrameworkElement>();
        #endregion

        #region 依赖属性
        public ObservableCollection<TabNavItem> Menus
        {
            get { return (ObservableCollection<TabNavItem>)GetValue(MenusProperty); }
            set { SetValue(MenusProperty, value); }
        }

        public static readonly DependencyProperty MenusProperty =
            DependencyProperty.Register("Menus", typeof(ObservableCollection<TabNavItem>), typeof(UTabControl), new PropertyMetadata(null, OnProppertyChanged));

        #endregion

        #region 依赖方法
        private static void OnProppertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ObservableCollection<TabNavItem> oldVals = (ObservableCollection<TabNavItem>)e.OldValue;
            ObservableCollection<TabNavItem> newVals = (ObservableCollection<TabNavItem>)e.NewValue;
            if (oldVals != newVals)
            {
                (d as UTabControl)?.UpdateMenus(newVals);
            }
        }

        private void UpdateMenus(ObservableCollection<TabNavItem> newVals)
        {
            rightMenu.Items.Clear();
            rightMenu.ItemsSource = newVals;

            ElemDict.Clear();
            foreach (var item in newVals)
            {
                ElemDict.Add(item.NavName,item.Element);
            }
        }

        #endregion

        #region 命令
        public ICommand ToTargetNavCommand { get; private set; }

        #endregion

        #region 命令方法
        private void ToTargetNav(TabNavItem tabItem)
        {
            try
            {
                if (string.IsNullOrEmpty(tabItem.NavName))
                    throw new Exception("NavName 地址不能为空");

                if (!ElemDict.ContainsKey(tabItem.NavName))
                {
                    throw new Exception($"对应的类型找不到: {tabItem.NavName}");
                }

                mainContent.Content = ElemDict[tabItem.NavName];
            }
            catch (Exception ex)
            {
                MsgBoxManager.Error(ex.Message);
            }
        }

        #endregion
    }


}
